package com.gz.thread.juc.collection;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

public class ListDemo {
    public static void main(String[] args) {
     //   notSafeList();
     //   vectorList();
        cowList();
    }

    //不安全的集合--->  异常
    public static void notSafeList(){
        List<String> strings = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                strings.add(UUID.randomUUID().toString().substring(0,5));
                strings.forEach(System.out::print);
            },String.valueOf(i)).start();
        }
        strings.forEach(System.out::println);
    }

   //  线程安全的集合
    public static void vectorList(){
        List<String> strings = new Vector<>();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                strings.add(UUID.randomUUID().toString().substring(0,5));
                strings.forEach(System.out::println);
            },String.valueOf(i)).start();
        }
    }

    //  线程安全的集合
    public static void cowList(){
        List<String> strings = new CopyOnWriteArrayList<>();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                strings.add(UUID.randomUUID().toString().substring(0,5));
                strings.forEach(System.out::print);
            },String.valueOf(i)).start();
        }
    }

    //  线程安全的集合
    public static void collList(){
        List<String> strings = Collections.synchronizedList(new ArrayList<>());
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                strings.add(UUID.randomUUID().toString().substring(0,5));
                strings.forEach(System.out::print);
            },String.valueOf(i)).start();
        }
    }
}

